//@ts-check
// @ts-ignore
import request from '@/router/axios'

/**
 * 5秒内重复拉取相同的请求会缓存
 */

/**@typedef {{delayTime: number, res: any, startTime: number, postData: object}} cacheObj*/
/**@typedef {{[x: string]: cacheObj}} cache*/
/**@type { cache } */
const $$apiCache_api = {}

/**
 * 获取缓存data
 * @param {string} key 
 * @returns {any} 
 */
function getCacheData(key, postData) {
  let nowTime = new Date().getTime()
  if (!$$apiCache_api[key]) {
    return null
  }
  // cache过期
  const { delayTime, startTime } = $$apiCache_api[key]
  if (nowTime - startTime > delayTime * 1000) {
    return null
  }
  // 请求参数不同
  if (JSON.stringify(postData) !== JSON.stringify($$apiCache_api[key].postData)) {
    return null
  }
  return $$apiCache_api[key].res
}

/**
 * 储存catch
 * @param {string} key 
 * @param {any} res 
 * @param {number} delayTime 
 */
function setCacheData(key, res, postData = {}, delayTime) {
  const nowTime = new Date().getTime()
  $$apiCache_api[key] = {
    delayTime,
    res,
    postData,
    startTime: nowTime
  }
}

/**
 * @param {object} option
 * @param {number} delayTime
 * @returns {object}
 */
export default  function requestCache(option, delayTime = 5) {
  return new Promise((resolve, reject) => {
    const cacheData = getCacheData(option.url, option.data)
    if (cacheData) {
      resolve(cacheData)
      return
    }
    request(option).then((res) => {
      setCacheData(option.url, res.data.data, option.data, delayTime)
      resolve(res.data.data)
    }).catch(error => {
      reject(error.message || error)
    })
  })
}
